package com.mc.jf.config;


import com.mc.jf.entity.PlanUser;
import com.mc.jf.utils.FastJsonUtils;
import com.mc.jf.utils.JwtUtil;
import com.mc.jf.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //1、获取token
        String token = request.getHeader("token");
        System.out.println(request.getRequestURI() + "=========token:" + token);

        Cookie[] cookies = request.getCookies();
        if ( !StringUtils.hasText(token) && cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                    System.out.println(request.getRequestURI() + "=========cookie-token:" + token);
                    break;
                }
            }
        }

        if (!StringUtils.hasText(token)) {
            //放行，让后面过滤器报错
            filterChain.doFilter(request, response);
            return;
        }

        //解析token
        String username = null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            filterChain.doFilter(request, response);
            return;
        }

        //获取userid
        PlanUser user = null;
        try {
            user = FastJsonUtils.fromJson(redisCache.getCacheObject("userid:" + username), PlanUser.class);
            if (Objects.isNull(user)) {
                System.out.println("token解析失败");
                filterChain.doFilter(request, response);
                return;
            }
        } catch (Exception e) {
            System.out.println("token解析失败");
            filterChain.doFilter(request, response);
            return;
        }

        //封装authentication
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        //存入securityContextHolder
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(request, response);

    }
}
